<?php

namespace App\Services;


use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class DogecoinService
{
    /**
     * @var \GuzzleHttp\Client
     */
    public $http;

    /**
     * ETHService constructor.
     */
    public function __construct()
    {
        $this->http = new Client();
    }

    public function newAccount($index)
    {
        return self::request('getnewaddress', [(string)$index, 'legacy']);
    }

    public function listTransactions($params = [])
    {
        return self::request('listtransactions', $params);
    }

    public function transfer($address, $amount)
    {
        return self::request('sendtoaddress', [$address, $amount]);
    }

    public function walletInfo($params = [])
    {
        return self::request('getwalletinfo', $params);
    }

    protected function request($method, $params = [])
    {
        $response = $this->http->post(config('doge.rpc.url'), [
            'timeout' => config('doge.rpc.timeout'),
            'auth' => config('doge.rpc.auth'),
            'json' => [
                'id' => time(),
                'jsonrpc' => '1.0',
                'method' => $method,
                'params' => $params,
            ],
        ]);

        $content = json_decode($response->getBody()->getContents(), true);
        if (null !== $content['error']) {
            Log::error(json_encode($content['error']));
            throw new \Exception('RPC ERROR');
        }

        return $content['result'];
    }

    public function __call($name, $arguments)
    {
        return self::request($name, $arguments);
    }
}
